package cn.broadmax.boot.modules.sys.service.impl;

import cn.broadmax.boot.modules.sys.bean.SysUserBean;
import cn.broadmax.boot.modules.sys.entity.SysUser;
import cn.broadmax.boot.modules.sys.service.ISysUserRoleService;
import cn.broadmax.boot.modules.sys.service.ISysUserService;
import cn.broadmax.boot.exception.WebException;
import cn.broadmax.boot.modules.sys.bean.user.UserCreateRequest;
import cn.broadmax.boot.modules.sys.mapper.SysUserMapper;
import cn.broadmax.boot.util.PasswordUtils;
import cn.broadmax.boot.util.SAssert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jexx.random.RandomUtil;
import jexx.util.CollectionUtil;
import jexx.util.RegexUtil;
import jexx.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 管理平台用户 服务实现类
 * </p>
 *
 * @author jexx
 * @since 2020-07-21
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    private final ISysUserRoleService sysUserRoleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUser addUser(UserCreateRequest request) {
        SAssert.notNull(request);
        String username = StringUtil.trim(request.getUsername());
        String password = StringUtil.trim(request.getPassword());
        String phone = StringUtil.isEmpty(request.getPhone()) ? "" : StringUtil.trim(request.getPhone());
        String email = StringUtil.isEmpty(request.getEmail()) ? "" : StringUtil.trim(request.getEmail());

        SAssert.hasText(password,"密码不能为空");
        checkUsername(null, username);
        checkPhone(null, phone);
        checkEmail(null, email);

        SysUser user = new SysUser();
        user.setUsername(username);
        user.setPhone(phone);
        user.setEmail(email);
        String salt = RandomUtil.randomAlphaNumeric(8);
        user.setSalt(salt);
        user.setPassword(PasswordUtils.encrypt(password, salt));
        user.setRealName(request.getRealName());
        user.setAvatar(request.getAvatar());
        user.setSex(request.getSex());
        user.setLocked(false);
        super.save(user);

        List<String> roleIds = request.getRoleIds();
        if(CollectionUtil.isNotEmpty(roleIds)){
            sysUserRoleService.appointRoleForUser(user.getId(), roleIds);
        }

        return getById(user.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUser updateUserById(String userId, SysUserBean user) {
        SAssert.notNull(user);
        String username = StringUtil.trim(user.getUsername());
        String phone = StringUtil.isEmpty(user.getPhone()) ? "" : StringUtil.trim(user.getPhone());
        String email = StringUtil.isEmpty(user.getEmail()) ? "" : StringUtil.trim(user.getEmail());

        checkUsername(userId, username);
        checkPhone(userId, phone);
        checkEmail(userId, email);

        SysUser update = new SysUser();
        update.setId(userId);
        if(StringUtil.isNotEmpty(username)){
            update.setUsername(username);
        }
        if(StringUtil.isNotEmpty(phone)){
            update.setPhone(phone);
        }
        if(StringUtil.isNotEmpty(email)){
            update.setEmail(email);
        }
        update.setUsername(username);
        update.setEmail(email);
        update.setPhone(phone);
        update.setRealName(user.getRealName());
        update.setAvatar(user.getAvatar());
        update.setSex(user.getSex());
        super.updateById(update);

        List<String> roleIds = user.getRoleIds();
        if(CollectionUtil.isNotEmpty(roleIds)){
            sysUserRoleService.appointRoleForUser(user.getId(), roleIds);
        }

        return getById(user.getId());
    }

    @Override
    public SysUser getSysUserByUserName(String userName) {
        if(StringUtil.isEmpty(userName)){
            return null;
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, userName);
        return super.getOne(wrapper);
    }

    @Override
    public SysUser getSysUserByPhone(String phone) {
        if(StringUtil.isEmpty(phone)){
            return null;
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getPhone, phone);
        return super.getOne(wrapper);
    }

    @Override
    public SysUser getSysUserByEmail(String email) {
        if(StringUtil.isEmpty(email)){
            return null;
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getEmail, email);
        return super.getOne(wrapper);
    }

    @Override
    public SysUser dynamicFindSysUser(String str) {
        if(StringUtil.isEmpty(str)){
            return null;
        }

        SysUser user;
        if(str.contains("@")){
            user = getSysUserByEmail(str);
        }
        else if(StringUtil.isNumeric(str)){
            user = getSysUserByPhone(str);
        }
        else{
            user = getSysUserByUserName(str);
        }
        return user;
    }

    private void checkUsername(String userId, String username){
        if(userId == null){
            if(StringUtil.isEmpty(username)){
                throw new WebException("用户名不能为空");
            }
        }
        else{
            if(StringUtil.isEmpty(username)){
                return;
            }
        }

        SysUser user = getSysUserByUserName(username);
        if(user != null){
            if(userId == null || !userId.equals(user.getId())){
                throw new WebException("用户名已存在");

            }
        }
    }

    private void checkPhone(String userId, String phone){
        if(StringUtil.isEmpty(phone)){
            return;
        }
        if(!RegexUtil.isMobilePhoneInChinese(phone)){
            throw new WebException("手机号不符合要求");
        }

        SysUser user = getSysUserByPhone(phone);
        if(user != null){
            if(userId == null || !userId.equals(user.getId())){
                throw new WebException("手机号已存在");
            }
        }
    }

    private void checkEmail(String userId, String email){
        if(StringUtil.isEmpty(email)){
            return;
        }
        if(!RegexUtil.isEmail(email)){
            throw new WebException("邮箱不符合要求");
        }

        SysUser user = getSysUserByEmail(email);
        if(user != null){
            if(userId == null || !userId.equals(user.getId())){
                throw new WebException("邮箱已存在");

            }
        }
    }

}
